package com.ruoyi.common.oss;

import com.ruoyi.common.utils.PropertiesUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;


/**
 * 本地上传服务
 * Created by Simaa on 2018-03-13 11:58.
 */
public class LocalFileStorageService {

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    public static String upload(MultipartFile file, String source, String title) throws Exception {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String root = PropertiesUtils.get("file_path");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = "";
        if(StringUtils.isBlank(title)) {
            path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + DateUtils.format(new Date(), "HHmmssS") + uuid.substring(0, 5);
        } else {
            path = title;
        }

        if (StringUtils.isNotBlank(prefix)) {
            if(StringUtils.isNotBlank(source)) {
                path = root + "/"+source+"/" + path + "." + prefix;
            } else {
                path = root + "/images/" + path + "." + prefix;
            }
        }
        File dir = new File(path);
        if (!dir.getParentFile().exists()) {
            dir.getParentFile().mkdirs();
        }
        file.transferTo(new File(path));
        String url = path.replace(root, "");
        if(!url.startsWith("/")) {
            url = "/" + url;
        }
        url = "/images" + url;
        return url;
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file, Long source) throws Exception {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String root = PropertiesUtils.get("file_path");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + DateUtils.format(new Date(), "HHmmssS") + uuid.substring(0, 5);

        if (StringUtils.isNotBlank(prefix)) {
            path = root + "/material/" + source + "/original" +"." + prefix;
        }
        File dir = new File(path);
        if (!dir.getParentFile().exists()) {
            dir.getParentFile().mkdirs();
        }
        file.transferTo(new File(path));
        String url = path.replace(root, "");
        if(!url.startsWith("/")) {
            url = "/" + url;
        }
        return url;
    }
}
